package com.zsjp.alc.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;

import com.zsjp.alc.entity.ErrorMessage;
/**
 * 解析错误配置文件的工具包
 * */
public class ParseErrorUtil {
	/**
	 * 用DOM方式读取error.xml文件
	 */
    private static DocumentBuilderFactory dbFactory = null;
    private static DocumentBuilder db = null;
    private static Document document = null;
    public static Map<String, ErrorMessage> errorMap  = new HashMap<String, ErrorMessage>();
    static{
    	try {
            dbFactory = DocumentBuilderFactory.newInstance();
            db = dbFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
    }

    public static Map<String, ErrorMessage> getErrorMap(String fileName) throws Exception{
        //将给定 URI 的内容解析为一个 XML 文档,并返回Document对象
        document = db.parse(fileName);
        //按文档顺序返回包含在文档中且具有给定标记名称的所有 Element 的 NodeList
        NodeList errorList = document.getElementsByTagName("error");
        //遍历books
        for(int i=0;i<errorList.getLength();i++){
            ErrorMessage error = new ErrorMessage();
            //获取第i个ErrorMessage结点
            org.w3c.dom.Node node = errorList.item(i);
            //获取第i个errorMessage的所有属性
            NamedNodeMap namedNodeMap = node.getAttributes();
            //获取已知名为id的属性值
            String id = namedNodeMap.getNamedItem("id").getTextContent();//System.out.println(id);
            error.setErrorCode(id);
            //获取error结点的子节点
            NodeList cList = node.getChildNodes();//System.out.println(cList.getLength());9
            System.out.println(cList.getLength());
            //将一个error里面的属性加入数组
            ArrayList<String> contents = new ArrayList<>();
            for(int j=1; j<cList.getLength(); j+=2){
                org.w3c.dom.Node cNode = cList.item(j);
                String content = cNode.getFirstChild().getTextContent();
                contents.add(content.trim());
            }

            error.setDescription(contents.get(0));
            error.setSuggestion(contents.get(1));
            errorMap.put(id, error);
        } 
        return errorMap;
    }
}
